﻿using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
using UnityEngine.EventSystems;

namespace Lost{
	///射线检测信息
	public struct HitInf{
		public bool isUI;
		public float distance;
		public Vector3 point;
		public GameObject hitObj;
	};
	/// <summary>
	/// 迷失交互，输入-->交互-->物品动作
	/// </summary>
	public class LostInteraction : MonoBehaviour {
		///脚本本身
		public static LostInteraction _instance;

		///中心点
		[SerializeField] string centerPointName = "CenterPoint";
		Transform centerPoint;
		///当objGazed==null时，中心点放置的距离
		[SerializeField] float disWhileNull = 10f;
		///中心点的原始比例大小
		Vector3 regionScale;
		///射线检测信息
		HitInf hitInf;
		///主摄像机
		Transform mCamera;

		///上一次获取被凝视物体时的时间
		//float curTime = -1f;


		void Awake(){
			_instance = this;
			mCamera = Camera.main.transform;
		}

		void Start(){
			centerPoint = ItemsManager.FindTransform (centerPointName);
			regionScale = centerPoint.localScale;
		}

		void LateUpdate () {
			RayCast ();
			centerPoint.position = hitInf.point;
			centerPoint.localScale = regionScale * hitInf.distance / disWhileNull;
			centerPoint.LookAt (centerPoint.position * 2 - mCamera.position);
			if (MyInput.GetInputOfType (InputType.CONFIRM)) {
				if (hitInf.hitObj != null && !hitInf.isUI) {
					GameObject objGazed = hitInf.hitObj;
					InteractiveItem ii = objGazed.GetComponent<InteractiveItem> ();
					if (ii != null) {
						ii.Interact (hitInf);
					} else {
						Transform parent = objGazed.transform.parent;
						if (parent != null) {
							ii = parent.GetComponent<InteractiveItem> ();
							if (ii != null) {
								ii.Interact (hitInf);
							}
						}
					}
					//objGazed.SendMessage ("OnInteraction", hitInf, SendMessageOptions.DontRequireReceiver);
					//if (objGazed.transform.parent != null) {
					//	objGazed.transform.parent.SendMessage ("OnInteraction", hitInf, SendMessageOptions.DontRequireReceiver);
					//}
				}
			}
		}

		/// <summary>
		/// 用射线检测场景，可能检测到的是3D物体，也可能是UI
		/// 信息存储到hitResult中
		/// </summary>
		void RayCast(){
			RaycastHit hit;
			Ray ray = new Ray (mCamera.position, mCamera.forward);
			if (Physics.Raycast (ray, out hit, disWhileNull, LayerMask.NameToLayer("Player"))) {
				hitInf.point = hit.point;
				hitInf.hitObj = hit.transform.gameObject;
				hitInf.distance = hit.distance;
			} else {
				hitInf.point = mCamera.position + mCamera.forward * disWhileNull;
				hitInf.hitObj = null;
				hitInf.distance = disWhileNull;
			}
			hitInf.isUI = false;
			foreach (RaycastResult rr in GetUIRaycast(hitInf.point)) {
				float dis = rr.distance + Camera.main.nearClipPlane;
				if (dis <= hitInf.distance) {
					hitInf.isUI = true;
					hitInf.distance = dis;
					hitInf.point = mCamera.position + mCamera.forward * hitInf.distance;
					hitInf.hitObj = rr.gameObject;
				}
			}
		}
		/// <summary>
		/// 用 从主摄像机到lookPoint 的射线检测场景中的所有UI
		/// 返回UI中hitPoint点的所有UI物体
		/// </summary>
		/// <returns>The user interface raycast.</returns>
		/// <param name="lookPoint">Look point.</param>
		List<RaycastResult> GetUIRaycast(Vector3 lookPoint){
			if (centerPoint == null) {
				return null;
			}
			Vector3 screenPos = Camera.main.WorldToScreenPoint (lookPoint);
			Vector2 screenPos2 = new Vector2 (screenPos.x, screenPos.y);
			List<RaycastResult> rrs = new List<RaycastResult> ();
			PointerEventData ped = new PointerEventData (EventSystem.current);
			ped.position = screenPos2;
			foreach (GraphicRaycaster gr in GameObject.FindObjectsOfType<GraphicRaycaster>()) {
				gr.Raycast (ped, rrs);
			}
			return rrs;
		}

		//是否显示射线
		[SerializeField] bool isShowLine = true;
		void OnDrawGizmos(){
			if (isShowLine) {
				DrawRayToCenterPoint ();
			}
		}
		void DrawRayToCenterPoint(){
			if (centerPoint != null) {
				Gizmos.DrawLine (Camera.main.transform.position, centerPoint.position);
			}
		}

	}
}
